import { Data } from '@/api/types/common'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/permit.ts'
import { useUserStore } from '@/store/modules/user.ts'
import {Obj} from "@/types/common";

const userStore = useUserStore()
//创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 50000,
})
//请求拦截器
request.interceptors.request.use((config) => {
  // config.headers['Content-Type'] = 'application/json'
  config.headers['tenant-id'] = 1
  config.headers['Authorization'] = 'Bearer ' + userStore.userInfo.token
  return config
})
//响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.data.code === 503) {
      userStore.removeUserInfo()
      return router.push('/login')
    }
    return response.data
  },
  (error) => {
    //处理网络错误
    let msg = ''
    let type = 'error';
    const status = error.response?.status
    switch (status) {
      case 401:
        msg = 'token过期'
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现问题'
        break
      default:
        if(error.code !== 'ERR_CANCELED') {
          msg = '无网络'
        } else {
          type = 'success'
          msg = '上传取消'
        }
    }
    ElMessage({
      type: type,
      message: msg,
    })
    return Promise.reject(error)
  },
)
export default request

export function Get<T>(url: string, params?: any, data?: any) {
  return request.get<any, Data<T>>(url, { params, data })
}
export function Post<T>(url: string, data?: any, params?: any, headers?: any, onUploadProgress?:Function, controller?: Object) {
  return request.post<any, Data<T>>(url, data, { params, headers, onUploadProgress, signal: controller?.signal })
}
export function Put<T>(url: string, data?: any) {
  return request.put<any, Data<T>>(url, data)
}
export function Delete<T>(url: string, data?: any) {
  return request.delete<any, Data<T>>(url, { params: data })
}
